<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="入库单编号" prop="recptCode">
            <el-input v-model="queryParams.recptCode" placeholder="请输入入库单编号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入库单名称" prop="recptName">
            <el-input v-model="queryParams.recptName" placeholder="请输入入库单名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商名称" prop="vendorName">
            <el-input v-model="queryParams.vendorName" placeholder="请输入供应商名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入库日期" prop="recptDate">
            <el-date-picker clearable v-model="queryParams.recptDate" type="datetime" format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择入库日期" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['recpt:recpt:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['recpt:recpt:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['recpt:recpt:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['recpt:recpt:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库单ID" align="center" prop="recptId" />
      <el-table-column label="入库单编号" align="center" prop="recptCode" />
      <el-table-column label="入库单名称" align="center" prop="recptName" />
      <el-table-column label="供应商名称" align="center" prop="vendorName" />
      <el-table-column label="入库日期" align="center" prop="recptDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="单据状态" align="center" prop="status" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['recpt:recpt:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['recpt:recpt:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageDto.current"
      v-model:limit="queryParams.pageDto.size" @pagination="getList" />

    <!-- 添加或修改物料入库单对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="recptRef" :model="form" :rules="rules" label-width="120px">
        <!-- 入库单编号 -->
        <el-form-item label="入库单编号" prop="recptCode">
          <el-input style="width: 300px;" v-model="form.recptCode" placeholder="请输入入库单编号" />
          <el-switch v-model="value1" @change="handleChange" style="margin-left: 10px;" />
          <span style="margin-left: 5px;">自动生成</span>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库单名称" prop="recptName">
              <el-input v-model="form.recptName" placeholder="请输入入库单名称" style="width: 300px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库日期" prop="recptDate">
              <el-date-picker v-model="form.recptDate" type="date" placeholder="请选择入库日期" format="YYYY-MM-DD"
                style="width: 300px;" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 供应商 -->
        <el-form-item label="供应商" prop="vendorCode">
          <el-input v-model="form.vendorCode" placeholder="请选择供应商" style="width: 300px;" />
          <el-button size="small"
            style="margin-left: 10px; width: 30px; height: 30px; border: 1px solid #DCDFE6; background-color: #F5F7FA; cursor: pointer;"
            @click="vendorVisible = true, getListVendor()">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" style="width: 800px;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>


      <!-- 供应商选择弹窗 -->
      <el-dialog v-model="vendorVisible" width="1200" title="供应商选择" center append-to-body>
        <div class="app-container">
          <el-form :model="proParams" ref="queryRefVendor" :inline="true" v-show="showSearch" label-width="120px">
            <el-row :gutter="24">
              <!-- 供应商编码 -->
              <el-col :span="7">
                <el-form-item label="供应商编码" prop="vendorCode">
                  <el-input v-model="proParams.vendorCode" placeholder="请输入供应商编码" clearable
                    @keyup.enter="handleQueryVendor" />
                </el-form-item>
              </el-col>

              <!-- 供应商名称 -->
              <el-col :span="8">
                <el-form-item label="供应商名称" prop="vendorName">
                  <el-input v-model="proParams.vendorName" placeholder="请输入供应商名称" clearable
                    @keyup.enter="handleQueryVendor" />
                </el-form-item>
              </el-col>

              <!-- 供应商简称 -->
              <el-col :span="6">
                <el-form-item label="供应商简称" prop="vendorNick">
                  <el-input v-model="proParams.vendorNick" placeholder="请输入供应商简称" clearable
                    @keyup.enter="handleQueryVendor" />
                </el-form-item>
              </el-col>

              <!-- 供应商英文名称 -->
              <el-col :span="7">
                <el-form-item label="供应商英文名称" prop="vendorEn">
                  <el-input v-model="proParams.vendorEn" placeholder="请输入供应商英文名称" clearable
                    @keyup.enter="handleQueryVendor" />
                </el-form-item>
              </el-col>

              <!-- 是否启用 -->
              <el-col :span="9">
                <el-form-item label="是否启用" prop="enableFlag">
                  <el-input v-model="proParams.enableFlag" placeholder="请输入是否启用" clearable
                    @keyup.enter="handleQueryVendor" />
                </el-form-item>
              </el-col>

              <!-- 操作按钮 -->
              <el-col :span="6">
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQueryVendor">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQueryVendor">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-table v-loading="loading" :data="vendorList" :row-key="row => row.vendorId" highlight-current-row
            @current-change="handleCurrentChangeVendor" ref="vendorTableRef" @row-click="handleRowClick">
            <el-table-column width="55" align="center">
              <template #default="scope">
                <el-radio v-model="selectedVendorId" @change="handleRadioChange(scope.row)">
                </el-radio>
              </template>
            </el-table-column>
            <el-table-column label="供应商ID" align="center" prop="vendorId" />
            <el-table-column label="供应商编码" align="center" prop="vendorCode" />
            <el-table-column label="供应商名称" align="center" prop="vendorName" />
            <el-table-column label="供应商简称" align="center" prop="vendorNick" />
            <el-table-column label="供应商等级" align="center" prop="vendorLevel">
              <template #default="scope">
                <dict-tag :options="sys_md_vendorlevel" :value="scope.row.vendorLevel" />
              </template>
            </el-table-column>
            <el-table-column label="供应商评分" align="center" prop="vendorScore" />
            <el-table-column label="供应商电话" align="center" prop="tel" />
            <el-table-column label="是否启用" align="center" prop="enableFlag" />
            <el-table-column label="备注" align="center" prop="remark" />
          </el-table>

          <pagination v-show="totalVendor > 0" :total="totalVendor" v-model:page="proParams.pageNum"
            v-model:limit="proParams.pageSize" @pagination="getListVendor" />

          <div class="dialog-footer">
            <el-button type="primary" @click="confirmSelectedVendor">确 定</el-button>
            <el-button @click="cancelVendor">取 消</el-button>
          </div>
        </div>
      </el-dialog>



      <!-- 修改入库单时的选择物料的卡片 -->
      <el-card style="max-width: 1000px" v-show="flag1">
        <template #header>
          <div class="card-header">
            <span>物料信息</span>
          </div>
        </template>
        <!-- 物料信息表 -->
        <el-form :model="queryParamsWuLiao" ref="queryRefWuLiao" :inline="true" v-show="showSearch" label-width="68px">
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAddWL"
              v-hasPermi="['line:line:add']">新增物料</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDeleteWL"
              v-hasPermi="['line:line:remove']">删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getListWL"></right-toolbar>
        </el-row>
        <!-- 新增物料那一块的数据 -->
        <el-table v-loading="loading" :data="lineList">
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column label="产品物料编码" align="center" prop="itemCode" width="180" />
          <el-table-column label="产品物料名称" align="center" prop="itemName" />
          <el-table-column label="规格型号" align="center" prop="specification" />
          <el-table-column label="单位" align="center" prop="unitOfMeasure" width="80" />
          <el-table-column label="入库数量" align="center" prop="quantityRecived" width="80" />
          <el-table-column label="入库批次号" align="center" prop="batchCode" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdateWL(scope.row)"
                v-hasPermi="['line:line:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDeleteWL(scope.row)"
                v-hasPermi="['line:line:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="totalWL > 0" :total="totalWL" v-model:page="queryParamsWuLiao.pageDto.current"
          v-model:limit="queryParamsWuLiao.pageDto.size" @pagination="getListWL" />

        <!-- 修改物料入库单行弹窗，要填写入库数量 -->
        <el-dialog v-model="openUpdateLine" :title="titleRecptLine" width="1000px" append-to-body>
          <el-form :model="formRecptLine" ref="formRecptLineRef" :rules="rulesRecptLine" label-width="100px">
            <el-row :gutter="20">
              <!-- 物料编码行 -->
              <el-col :span="8">
                <el-form-item label="物料编码" prop="itemCode">
                  <div style="display: flex;">
                    <el-input v-model="formRecptLine.itemCode" placeholder="请输入物料编码" clearable />
                    <el-button icon="Search" @click="searchItem" />
                  </div>

                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物料名称" prop="itemName">
                  <el-input v-model="formRecptLine.itemName" placeholder="请输入物料名称" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="单位" prop="unitOfMeasure">
                  <el-input v-model="formRecptLine.unitOfMeasure" placeholder="请输入单位" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <!-- 入库数量行 -->
              <el-col :span="8">
                <el-form-item label="入库数量" prop="quantityRecived" required>
                  <el-input-number v-model="formRecptLine.quantityRecived" :min="1" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="生产日期" prop="createDate">
                  <el-date-picker v-model="formRecptLine.createDate" type="datetime" placeholder="请选择生产日期" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="有效期" prop="expiryDate">
                  <el-date-picker v-model="formRecptLine.expireDate" type="datetime" placeholder="请选择有效期" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <!-- 生产批号、批次号行 -->
              <el-col :span="8">
                <el-form-item label="入库批号" prop="batchCode">
                  <el-input v-model="formRecptLine.batchCode" placeholder="请输入生产批号" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <!-- 备注行 -->
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="formRecptLine.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <!-- 按钮行 -->
              <el-col :span="24" style="text-align: right;">
                <el-form-item>
                  <el-button type="primary" @click="submitFormRecptLine">确定</el-button>
                  <el-button @click="cancelFormRecptLine">取消</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- 选择物料的弹窗 -->
          <el-dialog v-model="visibleWL" title="物料产品选择" width="1200" :before-close="handleClose" apply-to-body>
            <div class="app-container">
              <el-container>
                <el-aside width="200px" style="background-color: white;">
                  <el-table style="border: none;" v-if="refreshTable" :data="type1List" row-key="itemTypeId"
                    :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                    @row-click="handleCategoryClick"> <!-- 新增：点击分类行触发查询 -->
                    <el-table-column align="center" prop="itemTypeName" />
                  </el-table>
                </el-aside>
                <el-main>
                  <el-form :model="itemQueryParams" ref="queryRefItem" :inline="true" v-show="showSearch"
                    label-width="68px">
                    <el-form-item label="物料编码" prop="itemCode">
                      <el-input v-model="itemQueryParams.itemCode" placeholder="请输入物料编码" clearable
                        @keyup.enter="handleQueryItem" />
                    </el-form-item>
                    <el-form-item label="物料名称" prop="itemName">
                      <el-input v-model="itemQueryParams.itemName" placeholder="请输入物料名称" clearable
                        @keyup.enter="handleQueryItem" />
                    </el-form-item>

                    <el-form-item>
                      <el-button type="primary" icon="Search" @click="handleQueryItem">搜索</el-button>
                      <el-button icon="Refresh" @click="resetQueryItem">重置</el-button>
                    </el-form-item>
                  </el-form>

                  <el-row :gutter="10" class="mb8">
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getItemList"></right-toolbar>
                  </el-row>

                  <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChangeItem">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="物料编码" align="center" prop="itemCode" />
                    <el-table-column label="物料名称" align="center" prop="itemName" />
                    <el-table-column label="规格型号" align="center" prop="specification" />
                    <el-table-column label="单位" align="center" prop="unitOfMeasure" />
                    <el-table-column label="物料/产品" align="center" prop="itemOrProduct" />
                    <el-table-column label="所属分类" align="center" prop="itemTypeName" />
                    <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                      <template #default="scope">
                        <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                      </template>
                    </el-table-column>
                  </el-table>
                  <pagination v-show="totalItem > 0" :total="totalItem" v-model:page="itemQueryParams.pageNum"
                    v-model:limit="itemQueryParams.pageSize" @pagination="getItemList" />
                </el-main>

              </el-container>
              <el-button style="margin-left: 950px;" type="primary" @click="confirmSelectedItem">确 认</el-button>
              <el-button @click="cancelItem">关 闭</el-button>
            </div>
          </el-dialog>
        </el-dialog>

      </el-card>
    </el-dialog>
  </div>
</template>

<script setup name="Recpt">
import { listRecpt, getRecpt, delRecpt, addRecpt, updateRecpt } from "@/api/recpt/recpt"
import { listVendor, getVendor, delVendor, addVendor, updateVendor } from "@/api/vendor/vendor"
import { addWmItemRecptLine, listItemRecptLine, updateWmItemRecptLine, delWmItemRecptLine, updateLine } from "@/api/line/line"
import { listItem, getItem, delItem, addItem, updateItem } from "@/api/item/item"
import { cang } from "@/api/issue/issue"
import { ref } from 'vue'
//---------------------------------------------------物料信息
const flag1 = ref(false)//是否显示物料增删卡片
const totalWL = ref(0)//入库单中新增的物料总数列表总数
const queryParamsWuLiao = ref({
  pageDto: {
    current: 1,
    size: 10,
  },
})
const visibleWL = ref(false)//物料选择框显示隐藏
const lineList = ref([])  // 物料列表数据
//物料分类树相关
import { listType1 } from "@/api/type1/type1"
const type1List = ref([])//存放物料分类数据
const isExpandAll = ref(true)
const refreshTable = ref(true)
const dataWL = reactive({
  queryParamsWL: {
  },
})
const { queryParamsWL } = toRefs(dataWL)

const titleRecptLine = ref("")
const totalItem = ref(0)//物料产品选择框中所有的物料产品总数
const itemList = ref([]); // 用于存储物料产品列表
// 定义物料专用查询参数
const itemQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  itemCode: null, // 物料编码
  itemName: null, // 物料名称
  itemTypeId: 1,
});

// 保存选中的物料数据
const selectedItems = ref([]);

//物料入库单行对象
const itemReceptLine = ref({
  recptId: null,//入库单ID
  itemId: null,//产品物料ID
  itemCode: null,//物料编码
  itemName: null,//物料名称
  specification: null,//规格型号
  unitOfMeasure: null,//单位
  quantityRecived: 0,//入库数量
  batchCode: null,//批次码
  createDate: null,//生产日期
  expireDate: null,//有效日期
})

//物料入库行对象
const formRecptLine = ref({
  recptId: null,//入库单ID
  itemId: null,//产品物料ID
  itemCode: null,//物料编码
  itemName: null,//物料名称
  specification: null,//规格型号
  unitOfMeasure: null,//单位
  quantityRecived: 0,//入库数量
  batchCode: null,//批次码
  createDate: null,//生产日期
  expireDate: null,//有效日期
  remark: null
})
const formRecptLineRef = ref(null)
const rulesRecptLine = {
  itemCode: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入入库数量', trigger: 'blur' }]
};

//修改物料入库单行确定按钮
async function submitFormRecptLine() {
  console.log("formRecptLine.value", formRecptLine.value);
  if (formRecptLine.value.lineId) {
    await updateWmItemRecptLine(formRecptLine.value).then(response => {
      if (response.success) {
        proxy.$modal.msgSuccess("修改成功")
      } else {
        proxy.$modal.msgError("修改失败")
      }
    })
  } else {
    await addWmItemRecptLine(formRecptLine.value).then(response => {
      console.log("tianjia ？？？？", response)
      if (response.success) {
        proxy.$modal.msgSuccess("添加成功")
      } else {
        proxy.$modal.msgError("添加失败")
      }
    })
  }

  cancelFormRecptLine()




  getListWL()


}
//修改物料入库单行取消按钮
function cancelFormRecptLine() {
  openUpdateLine.value = false
  // 重置表单数据
  formRecptLine.value = {
    recptId: form.value.recptId,
    lineId: null,
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    quantityRecived: 0,
    batchCode: null,
    createDate: null,
    expireDate: null,
    remark: null
  }

  // 清除验证状态
  nextTick(() => {
    if (formRecptLineRef.value) {
      formRecptLineRef.value.clearValidate()
    }
  })
}







// 添加物料按钮
function handleAddWL() {
  // 先重置表单数据
  formRecptLine.value = {
    recptId: form.value.recptId, // 保持入库单ID
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    quantityRecived: 0,
    batchCode: null,
    createDate: null,
    expireDate: null,
    remark: null
  }

  // 如果需要重置表单验证状态
  nextTick(() => {
    if (formRecptLineRef.value) {
      formRecptLineRef.value.clearValidate()
    }
  })
  openUpdateLine.value = true
  titleRecptLine.value = "添加物料入库单行"
}
//点击选择物料按钮
function searchItem() {
  getWLTypeList()//加载物料分类树
  //加载物料产品列表
  getItemList()


  visibleWL.value = true
  title1.value = "添加物料入库单行"
}

// 修改物料表单行按钮
function handleUpdateWL(row) {
  formRecptLine.value = row
  openUpdateLine.value = true
  titleRecptLine.value = "修改物料入库单行"

}

//删除物料按钮
function handleDeleteWL(row) {
  // console.log("row", row);
  // 提示确认
  proxy.$modal.confirm('是否确认删除物料入库单行为"' + row.itemName + '"的数据项？').then(async function () {
    await delWmItemRecptLine(row).then(response => {
      // console.log("删除了物料入库单行！！！", response);
    })
  }).then(() => {
    getListWL()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}
/** 查询物料入库单行列表 */
function getListWL() {
  // loading.value = true
  // console.log("物料入库单id", formRecptLine.value.recptId);
  listItemRecptLine(formRecptLine.value.recptId).then(response => {
    // console.log("物料入库单行列表", response);
    lineList.value = response.data.records
    totalWL.value = response.data.pageDto.total
    loading.value = false
  })
}

/** 查询物料分类列表 */
function getWLTypeList() {
  // loading.value = true
  listType1(queryParamsWL.value).then(response => {
    console.log("物料分类", response);

    type1List.value = proxy.handleTree(response.data, "itemTypeId", "parentTypeId")
    loading.value = false
  })
}
/** 新增：处理物料分类点击事件 */
function handleCategoryClick(row) {
  // 设置选中的分类ID到查询参数
  itemQueryParams.value.itemTypeId = row.itemTypeId
  // 重置页码为1
  itemQueryParams.value.pageNum = 1
  // 执行查询
  getItemList()
}


/** 查询物料产品管理列表 */
function getItemList() {
  loading.value = true
  listItem(itemQueryParams.value).then(response => {
    console.log("物料产品列表", response);
    itemList.value = response.rows
    totalItem.value = response.total
    loading.value = false
  })
}
//物料选择框搜索物料产品列表
function handleQueryItem() {
  itemQueryParams.value.pageNum = 1
  getItemList()
}
// 物料选择框重置
function resetQueryItem() {
  proxy.resetForm("queryRefItem")
  itemQueryParams.value.itemTypeId = 1
  itemQueryParams.value.pageNum = 1
  getItemList()
}
// 物料选择关闭按钮
function cancelItem() {
  visibleWL.value = false
  resetQueryItem()
}

//选择一个要入库的物料产品
function handleSelectionChangeItem(selection) {
  // 将选中的数据保存到selectedItems中
  selectedItems.value = selection;
}

// 确定选择物料产品,直接添加到入库单行单行表中
async function confirmSelectedItem() {
  if (selectedItems.value.length === 0) {
    // 如果没有选中数据，给出提示
    proxy.$modal.msgWarning("请先选择物料数据")
    return;
  }
  // 打印选中的第一条数据（如果只需要一条）
  console.log('选中的数据:', selectedItems.value[0]);
  formRecptLine.value.itemId = selectedItems.value[0].itemId
  formRecptLine.value.itemCode = selectedItems.value[0].itemCode
  formRecptLine.value.itemName = selectedItems.value[0].itemName
  formRecptLine.value.specification = selectedItems.value[0].specification
  formRecptLine.value.unitOfMeasure = selectedItems.value[0].unitOfMeasure
  visibleWL.value = false

}

//-----------------------------------------------新增采购入库单行
const openUpdateLine = ref(false)//新增采购入库单行弹窗显示隐藏









//------------------------------------------------------------采购入库单变量
const recptList = ref([])//采购入库单列表
const total = ref(0)//采购入库单总数
const showSearch = ref(true)
const loading = ref(true)
const open = ref(false)//采购入库表单弹窗
const title = ref("")//采购入库表单标题


const data = reactive({
  form: {},
  //采购入库单参数
  queryParams: {
    pageDto: {
      current: 1,
      size: 10,
    },
    recptCode: null,//采购入库单编号
    recptName: null,//采购入库单名称
    vendorName: null,//供应商名称
    recptDate: null,//入库日期
  },
  rules: {
    recptCode: [
      { required: true, message: "入库单编号不能为空", trigger: "blur" }
    ],
    recptName: [
      { required: true, message: "入库单名称不能为空", trigger: "blur" }
    ],
    itemCode: [
      { required: true, message: "产品物料编码不能为空", trigger: "blur" }
    ],
    quantityRecived: [
      { required: true, message: "入库数量不能为空", trigger: "blur" }
    ],
  },

})

const { queryParams, form, rules } = toRefs(data)
// 表单重置
function reset() {
  form.value = {
    recptId: null,
    recptCode: null,
    recptName: null,
    iqcId: null,
    iqcCode: null,
    poCode: null,
    vendorId: null,
    vendorCode: null,
    vendorName: null,
    vendorNick: null,
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    areaCode: null,
    areaName: null,
    recptDate: null,
    status: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("recptRef")
  proxy.resetForm("queryRef")
}

// 日期格式化函数
function formatDate(date) {
  if (!date) return null

  // 如果已经是 yyyy-MM-dd 格式，直接返回
  if (typeof date === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(date)) {
    return date
  }

  // 如果是 ISO 格式字符串，提取日期部分
  if (typeof date === 'string' && date.includes('T')) {
    return date.split('T')[0]
  }

  // 如果是 Date 对象，格式化为 yyyy-MM-dd
  if (date instanceof Date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  return date
}



//-------------------------------------------------------------采购入库单相关函数
/** 新增采购入库单按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  flag1.value = false
  title.value = "添加物料入库单"
}
/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  const _recptId = row.recptId || ids.value
  await getRecpt(_recptId).then(response => {
    flag1.value = true
    console.log("入库单信息", response);
    itemReceptLine.value.recptId = response.data.recptId
    formRecptLine.value.recptId = response.data.recptId
    // 格式化日期
    if (response.data.recptDate) {
      response.data.recptDate = formatDate(response.data.recptDate)
    }
    form.value = response.data
    open.value = true
    title.value = "修改物料入库单"
  })
  getListWL()//加载采购入库单所选择的物料产品列表
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _recptIds = row.recptId || ids.value
  proxy.$modal.confirm('是否确认删除物料入库单编号为"' + _recptIds + '"的数据项？').then(function () {
    return delRecpt(_recptIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('recpt/recpt/export', {
    ...queryParams.value
  }, `recpt_${new Date().getTime()}.xlsx`)
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recptId)
  single.value = selection.length != 1
  multiple.value = !selection.length
  selectedItem.value = selection.length > 0 ? selection[0] : null;
}
/** 采购入库单搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageDto.current = 1
  getList()
}
/** 查询物料入库单列表 */
function getList() {
  loading.value = true
  listRecpt(queryParams.value).then(response => {
    //给采购入库数据接收列表赋值
    recptList.value = response.data.records
    total.value = response.data.pageDto.total
    loading.value = false
  })
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // handleQuery()
}

/** 提交保存采购按钮 */
function submitForm() {
  proxy.$refs["recptRef"].validate(valid => {
    if (valid) {
      console.log("form.value", form.value);

      if (form.value.recptId != null) {
        updateRecpt(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRecpt(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}




//---------------------------------------------------------------------供应商信息
const { proxy } = getCurrentInstance()
const { sys_md_vendorlevel } = proxy.useDict('sys_md_vendorlevel')
const vendorVisible = ref(false)//供应商弹窗显示隐藏
const vendorList = ref([]) //供应商接收列表
const totalVendor = ref(0) //供应商总数
//供应商查询参数
const proParams = ref({
  pageNum: 1,
  pageSize: 10,
  vendorCode: null,
  vendorName: null,
  vendorNick: null,
  vendorEn: null,
  enableFlag: null,
})
// 重置供应商查询参数为初始值
const initVendorParams = ref({ ...proParams })

/** 查询供应商列表 */
function getListVendor() {
  loading.value = true
  listVendor(proParams.value).then(response => {
    console.log("供应商吃鹌鹑", response.data);
    response.data.records.forEach(item => {
      item.enableFlag = item.enableFlag == 1 ? "是" : "否"
    })
    vendorList.value = response.data.records
    totalVendor.value = response.data.pageDto.total
    loading.value = false
  })
}
// 供应商查询
function handleQueryVendor() {
  proParams.pageNum = 1
  getListVendor()
}
//供应商查询条件重置
function resetQueryVendor() {
  //重置proParams中的值
  proParams.value = { ...proParams }
  getListVendor()

}

const vendorTableRef = ref(null)
const selectedVendorId = ref(null) // 存储选中的供应商ID（基础类型）
//被选中的供应商行
const selectedRowVendor = ref(null)
// 行点击事件处理
function handleRowClick(row) {
  selectedRowVendor.value = row
  // 设置当前行为选中状态
  if (vendorTableRef.value) {
    vendorTableRef.value.setCurrentRow(row)
  }
}

function handleCurrentChangeVendor(row) {
  selectedRowVendor.value = row
  console.log("1", row);

}
// 单选框变化处理
function handleRadioChange(row) {
  selectedRowVendor.value = row
  console.log("2", row);
  // 设置当前行为选中状态
  if (vendorTableRef.value) {
    vendorTableRef.value.setCurrentRow(row)
  }
}

/** 确认选择供应商 */
function confirmSelectedVendor() {
  if (!selectedRowVendor.value) {
    proxy.$modal.msgWarning("请选择一个供应商")
    return
  }

  console.log("selectedRowVendor.value", selectedRowVendor.value);

  // 将选中的供应商信息回填到表单
  form.value.vendorCode = selectedRowVendor.value.vendorCode
  form.value.vendorName = selectedRowVendor.value.vendorName
  form.value.vendorId = selectedRowVendor.value.vendorId

  // 关闭供应商选择框
  vendorVisible.value = false
  // proxy.$modal.msgSuccess("选择成功")
}

/** 取消选择 */
function cancelVendor() {
  vendorVisible.value = false
  resetQueryVendor()
  selectedRowVendor.value = null // 清空选择
  if (vendorTableRef.value) {
    vendorTableRef.value.clearCurrentRow()
  }
}









//-----------------------------------------------------------------------------仓库位置获取
// 绑定的仓库选中值（数组形式，存储各级选中的value）
const cangkuvalue = ref([])
const cangkuoptions = ref([])
//查询仓库
cangku()
function cangku() {
  const result = cang();
  // console.log("仓库");
  //console.log(result);
  result.then(res => {
    // console.log(res);
    cangkuoptions.value = res.data
    //  console.log(cangkuoptions.value);
    //  console.log("转换后的数据：", formattedOptions.value);

  })
}

// 转换后的数据（供级联选择器使用）
const formattedOptions = computed(() => {
  // 递归转换函数：将原始数据转为级联选择器格式
  const convert = (data) => {
    return data.map(item => {
      // 仓库级节点
      const warehouseNode = {
        value: item.warehouseId,  // 仓库ID作为value
        label: item.warehouseName, // 仓库名称作为label
        children: []
      };

      // 处理库区子节点
      if (item.storageLocationList && item.storageLocationList.length) {
        warehouseNode.children = item.storageLocationList.map(location => {
          const locationNode = {
            value: location.locationId,  // 库区ID作为value
            label: location.locationName, // 库区名称作为label
            children: []
          };

          // 处理库位子节点
          if (location.storageAreaList && location.storageAreaList.length) {
            locationNode.children = location.storageAreaList.map(area => ({
              value: area.areaId,  // 库位ID作为value
              label: area.areaName  // 库位名称作为label
            }));
          }

          return locationNode;
        });
      }

      return warehouseNode;
    });
  };
  // 调用转换函数处理原始数据
  return convert(cangkuoptions.value);
});











function handleChange(value) {
  if (value) {
    form.value.recptCode = 'WK' + new Date().getTime()
  } else {
    form.value.recptCode = ''
  }
}

//工单编码自动生成按钮是否显示
const value1 = ref(false)







const open1 = ref(false)


const ids = ref([])
const single = ref(true)
const multiple = ref(true)




const title1 = ref("")











// 取消按钮
function cancel() {
  open.value = false
  reset()
}


// 取消按钮
function cancel2() {
  open1.value = false
  reset()
}












getList()//获取采购入库列表
</script>


<style scoped>
.app-container {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-form-item__label {
  font-weight: bold;
  color: #333;
}

.el-input,
.el-date-editor {
  width: 200px;
}

.el-button {
  margin-left: 10px;
}
</style>